package com.mingqijia.gassafety.shared.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gap.basic.exception.BizException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.constant.MbpConst;
import com.mingqijia.gassafety.shared.constant.ThreeQuotientConstants;
import com.mingqijia.gassafety.shared.request.ThreeQuotientCreateReq;
import com.mingqijia.gassafety.shared.response.ThreeQuotientAddOrderResp;
import com.mingqijia.gassafety.shared.response.ThreeQuotientByOrderIDListResp;
import com.mingqijia.gassafety.shared.response.ThreeQuotientByOrderIDResp;
import com.mingqijia.gassafety.shared.service.ThreeQuotientService;
import com.mingqijia.gassafety.shared.utils.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class ThreeQuotientServiceImpl implements ThreeQuotientService {

    @Value(value = "${three.quotient.url}")
    String otherUrl;

    @Autowired
    HttpUtil httpUtil;

    @Autowired
    RedisTemplate redisTemplate;


    //获取token
    @Override
    public String getToken() {
        String url = otherUrl + String.format(ThreeQuotientConstants.REST_TOKEN, "FrGpsAlarm", "766527762065003153AEFA558060B875");
        log.info("开始请求获取token接口：{}", url);
        String body = httpUtil.getBody(url);
        JSONObject jsonObject = JSONObject.parseObject(body);
        if (jsonObject.get("errcode").equals("0") && !StringUtils.isEmpty(jsonObject.getString("token"))) {
            return jsonObject.getString("token");
        } else {
            String msg = jsonObject.get("errmsg")!=null?jsonObject.getString("errmsg"):"登录失败";
            throw new BizException(msg);
        }
    }

    //新增抢修单推送到管网系统
    @Override
    public ThreeQuotientAddOrderResp addRPSData(ThreeQuotientCreateReq req) {
        // 从Redis获取token
        String token = (String)redisTemplate.opsForValue().get(Constants.THREE_QUOTITENT_REDIS_KEY);
        if (StringUtils.isEmpty(token)) {
            token = getToken();
            redisTemplate.opsForValue().set(Constants.THREE_QUOTITENT_REDIS_KEY, token, 2*60*60, TimeUnit.SECONDS);
        }
        Map<String, Object> bodyMap = new HashMap<>();
        bodyMap.put("token", token);
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String jsonString = gson.toJson(req);
        bodyMap.put("data", jsonString);
        log.info("addRPSData请求url:{},参数:{}",otherUrl + ThreeQuotientConstants.REST_ADDRPSDATA,jsonString);
        String body = httpUtil.getBody(JSONObject.toJSONString(bodyMap), otherUrl + ThreeQuotientConstants.REST_ADDRPSDATA, null);
        JSONObject jsonObject = JSONObject.parseObject(body);
        if (jsonObject.get("errcode").equals("0000") && !StringUtils.isEmpty(jsonObject.getString("data"))) {
            ThreeQuotientAddOrderResp addOrderResp = gson.fromJson(jsonObject.getString("data"), ThreeQuotientAddOrderResp.class);
            return addOrderResp;
        } else if (jsonObject.get("errcode").equals("1001") && !StringUtils.isEmpty(jsonObject.getString("errmsg")) && "token expired".equals(jsonObject.getString("errmsg"))) {
            // token过期了，重新获取token
            String newToken = getToken();
            // 将新token保存到redis
            redisTemplate.opsForValue().set(Constants.THREE_QUOTITENT_REDIS_KEY, newToken, 2*60*60, TimeUnit.SECONDS);
            // 再次调用方法
            return addRPSData(req);
        } else {
            String msg = jsonObject.get("errmsg")!=null?jsonObject.getString("errmsg")+"("+jsonObject.getString("data")+")":jsonObject.getString("data");
            log.error("新增抢修单推送到管网系统-error:{}", msg);
            throw new BizException(msg);
        }
    }

    //查询工单状态接口
    @Override
    public ThreeQuotientByOrderIDListResp getByOrderID(Map<String, Object> parms) {
        // 从Redis获取token
        String token = (String)redisTemplate.opsForValue().get(Constants.THREE_QUOTITENT_REDIS_KEY);
        if (StringUtils.isEmpty(token)) {
            token = getToken();
            redisTemplate.opsForValue().set(Constants.THREE_QUOTITENT_REDIS_KEY, token, 2*60*60, TimeUnit.SECONDS);
        }
        Map<String, Object> bodyMap = new HashMap<>();
        bodyMap.put("token", token);
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String jsonString = gson.toJson(parms);
        bodyMap.put("data", jsonString);
        String body = httpUtil.getBody(JSONObject.toJSONString(bodyMap), otherUrl + ThreeQuotientConstants.REST_GETORDERDETAIL, null);
        JSONObject jsonObject = JSONObject.parseObject(body);
        if (jsonObject.get("errcode").equals("0000")) {
            JSONArray jsonArray = jsonObject.getJSONArray("data");
            if (CollectionUtils.isEmpty(jsonArray)) {
                return null;
            }
            Object data = jsonArray.get(0);
            ThreeQuotientByOrderIDListResp orderIDListResp = gson.fromJson(data.toString(), ThreeQuotientByOrderIDListResp.class);
            return orderIDListResp;
        } else if (jsonObject.get("errcode").equals("1001") && !StringUtils.isEmpty(jsonObject.getString("errmsg")) && "token expired".equals(jsonObject.getString("errmsg"))) {
            // token过期了，重新获取token
            String newToken = getToken();
            // 将新token保存到redis
            redisTemplate.opsForValue().set(Constants.THREE_QUOTITENT_REDIS_KEY, newToken, 2*60*60, TimeUnit.SECONDS);
            // 再次调用方法
            return getByOrderID(parms);
        } else {
            String msg = StringUtils.isNotEmpty(jsonObject.getString("errmsg"))?jsonObject.getString("errmsg"):"新增抢修单推送到管网系统失败";
            log.error("新增抢修单推送到管网系统-error:{}", msg);
            throw new BizException(msg);
        }
    }

    @Override
    public Map<String, Object> queryOrderInfo(String orderNo) {
        Map<String, Object> result = new HashMap<>();
        int code = 1;
        List<Map<String, Object>> lists = new ArrayList<>();
        Map<String, Object> params = new HashMap<>();
        params.put("ID", orderNo);
        ThreeQuotientByOrderIDListResp byOrderIDResp = getByOrderID(params);
        if (null != byOrderIDResp) {
            code = 0;
            Map<String, Object> temp = new HashMap<>();
            String status = byOrderIDResp.getStatus();
            if (StringUtils.equals(status, "13")) { //已完成,归档
                temp.put("state", MbpConst.WORK_STATE_FINISH);
            } else if (StringUtils.equals(status, "3")) { //已取消
                temp.put("state", MbpConst.WORK_STATE_END);
            } else {
                temp.put("state", 0);
            }
            temp.put("finishtime", byOrderIDResp.getLastProcessDate());
            temp.put("processer", byOrderIDResp.getLastProcesser());
            temp.put("processerintro", byOrderIDResp.getLastProcesserintro());
            lists.add(temp);
        }
        result.put("code", code);
        result.put("data", lists);
        return result;
    }

    @Override
    public Map<String, ThreeQuotientByOrderIDListResp> queryOrderList(List<String> orderNos) {
        Map<String, ThreeQuotientByOrderIDListResp> result = new HashMap<>();
        try {
            for (String orderNo : orderNos) {
                try {
                    Map<String, Object> params = new HashMap<>();
                    params.put("ID", orderNo);
                    ThreeQuotientByOrderIDListResp byOrderIDResp = getByOrderID(params);
                    result.put(orderNo, byOrderIDResp);
                } catch (Exception e) {
                    log.error("查询工单状态接口异常：", e);
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(), e);
        }
        return result;
    }
}
